/*
 * voipdcexample by Markus Weissbacher weissbacher at gmail dot com
 *
 * This program is Free Software, released under the Lesser GNU General
 * Public License v2.0 http://www.gnu.org/licenses/gpl
 *
 * This program is an example for a client program for the Voice over IP
 * daemon.  It creates a socket to localhost:20000 and polls input from
 * the voipd. This demo implementation only prints out what is sent to it.
 *
 * 
 */


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

#define SOCKET_ERROR        -1
#define BUFFER_SIZE         100
#define HOST_NAME_SIZE      255

/*global variable to be reachable for signalhandler*/
int hSocket;				/*handle to socket*/

/*function definition*/
void sighandler();

int  main(int argc, char* argv[])
{
	struct hostent* pHostInfo;		/* holds info about a machine */
	struct sockaddr_in Address;		/* Internet socket address stuct */
	long nHostAddress;
	char pBuffer[BUFFER_SIZE];
	unsigned nReadAmount;
	char strHostName[HOST_NAME_SIZE];
	int nHostPort;

	strcpy(strHostName, "localhost"); 	/*add your target here*/
	nHostPort=20000;			/*voipd defaults to port 20000*/

	/* make a socket */
	hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(SOCKET_ERROR==hSocket)
	{
		printf("Could not make a socket\n");
		return 0;
	}

	/* get IP address from name */
	pHostInfo=gethostbyname(strHostName);
	/* copy address into long */
	memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);

	/* fill address struct */
	Address.sin_addr.s_addr=nHostAddress;
	Address.sin_port=htons(nHostPort);
	Address.sin_family=AF_INET;

	/* connect to host */
	if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address)) == SOCKET_ERROR)
	{
		printf("\nCould not connect to host\n");
		return 0;
	}

	/*catch all termination signals and end the process cleanly*/
	signal(SIGPIPE, sighandler);
	signal(SIGTERM, sighandler);
	signal(SIGINT, sighandler);

	while((nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE)))
	{
		/*add custom code here*/
		printf("read %s\n", pBuffer);
	} 
	printf("\nClosing socket\n");
	/* close socket */                       
	if(SOCKET_ERROR==close(hSocket))
	{
		printf("\nCould not close socket\n");
	}
	return 0;
}

void sighandler()
{
	if(close(hSocket) == SOCKET_ERROR)
	{
		printf("\nCould not close socket\n");
	}
	_exit(0);
}
